//
//  CoinListViewController.m
//  AppleMarket
//
//  Created by yangy on 02/11/2018.
//  Copyright © 2018 szgsy. All rights reserved.
//

#import "CoinListViewController.h"
// model
#import "CoinAssetModel.h"

@interface CoinListViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchControllerDelegate,UISearchBarDelegate,UISearchResultsUpdating>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray<CoinAssetModel*> *dataArray;
@property (nonatomic, strong) NSMutableArray<CoinAssetModel*> *searchAResults;
@property (nonatomic, strong) UISearchController *searchVC;
@end

@implementation CoinListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"选择币种";
    self.view.backgroundColor = [UIColor whiteColor];
    self.definesPresentationContext = YES;
    
    [self initUI];
}

- (void) initUI
{
    [self.view addSubview:self.tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(self.searchVC.isActive){
        return self.searchAResults.count;
    }else{
        return self.dataArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class])];
    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([UITableViewCell class])];
        cell.textLabel.font = kFontBold(17);
        cell.textLabel.textColor = kColorWithHex(0x0E304C);
        cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"selected"]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.textLabel.text = @"APPLE";
    
    if(self.searchVC.isActive){
        cell.textLabel.text = self.searchAResults[indexPath.row].Unit;
    }else{
        cell.textLabel.text = self.dataArray[indexPath.row].Unit;
    }
    
    if(self.selectModel && [self.selectModel.Unit isEqualToString:cell.textLabel.text]){
        cell.accessoryView.hidden = NO;
    }else{
        cell.accessoryView.hidden = YES;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 53;
}

- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if(!self.searchVC.isActive){
        NSMutableArray *indexTitles = [[NSMutableArray alloc] init];
        [self.dataArray enumerateObjectsUsingBlock:^(CoinAssetModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *word = [obj.Unit substringWithRange:NSMakeRange(0, 1)];
            if(![indexTitles containsObject:word]){
                [indexTitles addObject:word];
            }
        }];
        return indexTitles;
    }
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    if(!self.searchVC.isActive){
        __block NSInteger objectIndex = NSNotFound;
        [self.dataArray enumerateObjectsUsingBlock:^(CoinAssetModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if([[obj.Unit substringToIndex:1] isEqualToString:title]){
                objectIndex = idx;
                *stop = YES;
            }
        }];
        [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:objectIndex inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        return objectIndex;
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.searchVC.isActive){
        self.selectModel = self.searchAResults[indexPath.row];
    }else{
        self.selectModel = self.dataArray[indexPath.row];
    }
    
    if(self.SelectedHandler){
        self.SelectedHandler(self.selectModel);
    }
    
    if(!self.nextViewController){
         [self.navigationController popViewControllerAnimated:YES];
    }else{
        id viewController = [[self.nextViewController alloc] init];
        [viewController setValue:self.selectModel forKey:@"coinModel"];
        [self bh_PushViewController:viewController hiddenTabbar:YES];
    }
}

#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    NSString *text = searchController.searchBar.text;
    if(text.length == 0){
        self.searchAResults = [self.dataArray mutableCopy];
    }else{
        [self.searchAResults removeAllObjects];
        [self.dataArray enumerateObjectsUsingBlock:^(CoinAssetModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if([obj.Unit containsString:text]){
                [self.searchAResults addObject:obj];
            }
        }];
    }
    [_tableView reloadData];
}

- (void)willPresentSearchController:(UISearchController *)searchController
{
    self.searchAResults = [[NSArray arrayWithArray:self.dataArray] mutableCopy];
    [_tableView reloadData];
}

- (UITableView *)tableView
{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        [_tableView setDelegate:self];
        [_tableView setDataSource:self];
        [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [_tableView setTableFooterView:[UIView new]];
        [_tableView setSectionIndexColor:kColorWithHex(0x0E304C)];
        [_tableView setTableHeaderView:self.searchVC.searchBar];
    }
    return _tableView;
}

- (NSArray *)dataArray
{
    if(!_dataArray){
        _dataArray = [self.coinModels sortedArrayUsingComparator:^NSComparisonResult(CoinAssetModel*  _Nonnull obj1, CoinAssetModel*  _Nonnull obj2) {
            UniChar c1 = [obj1.Unit characterAtIndex:0];
            UniChar c2 = [obj2.Unit characterAtIndex:0];
            if(c1 > c2){
                return NSOrderedDescending;
            }else if(c1 < c2){
                return NSOrderedAscending;
            }else{
                return NSOrderedSame;
            }
        }];
    }
    return _dataArray;
}

- (UISearchController *)searchVC
{
    if(!_searchVC){
        _searchVC = [[UISearchController alloc] initWithSearchResultsController:nil];
        [_searchVC.searchBar setAutocapitalizationType:UITextAutocapitalizationTypeNone];
        _searchVC.searchBar.placeholder = @"请输入感兴趣的币种";
        _searchVC.searchBar.barTintColor = [UIColor whiteColor];
        _searchVC.searchBar.layer.borderWidth = 0;
        _searchVC.searchBar.layer.borderColor = [UIColor whiteColor].CGColor;
        _searchVC.searchBar.backgroundImage = [UIImage new];
        _searchVC.delegate = self;
        _searchVC.searchResultsUpdater = self;
        _searchVC.dimsBackgroundDuringPresentation = NO;
        UITextField *searchField = [self.searchVC.searchBar valueForKey:@"_searchField"];
        searchField.font = kFont(14);
        [searchField setValue:kColorWithHex(0xB2BBC4) forKeyPath:@"_placeholderLabel.textColor"];
    }
    return _searchVC;
}

@end
